import COS from "cos-js-sdk-v5";

let cos;
let SecretId = sessionStorage.getItem("SecretId");
let SecretKey = sessionStorage.getItem("SecretKey");
let Bucket = sessionStorage.getItem("Bucket");
let Region = sessionStorage.getItem("Region");

export const getInstance = () => {
  if (!cos) {
    cos = new COS({
      SecretId,
      SecretKey,
    });
  }
  return cos;
};

export const init = async (SecretId, SecretKey, Bucket, Region) => {
  const tempCos = new COS({
    SecretId,
    SecretKey,
  });
  SecretId = SecretId;
  SecretKey = SecretKey;
  Bucket = Bucket;
  Region = Region;
  return new Promise((resolve, reject) => {
    tempCos.headBucket(
      {
        Bucket,
        Region,
      },
      (err, data) => {
        if (data) {
          cos = tempCos;
          sessionStorage.setItem("SecretId", SecretId);
          sessionStorage.setItem("SecretKey", SecretKey);
          sessionStorage.setItem("Bucket", Bucket);
          sessionStorage.setItem("Region", Region);
          resolve();
        } else {
          reject(err.statusCode);
        }
      }
    );
  });
};

export const listBands = async () => {
  const res = await getInstance().getBucket({
    Bucket,
    Region,
    Prefix: "icon/",
  });
  const bandMap = res.Contents.reduce((pre, next) => {
    const [folder, file] = next.Key.slice(5).split("/");

    if (folder) {
      const arr = pre.get(folder) || [];
      if (file) {
        arr.push({ name: file.replace(".svg", ""), url: next.Key });
      } else {
        pre.set(folder, arr);
      }
    }
    return pre;
  }, new Map());
  return [...bandMap.entries()].map(([name, icons]) => ({
    name,
    icons,
  }));
};

export const saveBand = async (bandName) =>
  new Promise((resolve, reject) => {
    getInstance().putObject(
      {
        Bucket,
        Region,
        Key: `icon/${bandName}/`,
        Body: "",
      },
      function (err, data) {
        if (err) {
          reject(err);
        } else {
          resolve(data);
        }
        console.log(err || data);
      }
    );
  });

export const deleteBand = async (bandName) =>
  new Promise((resolve, reject) => {
    getInstance().getBucket(
      {
        Bucket,
        Region,
        Prefix: `icon/${bandName}/`,
      },
      function (listError, listResult) {
        if (listError) {
          reject(listError);
          return console.log("list error:", listError);
        }
        var Objects = listResult.Contents.map(function (item) {
          return { Key: item.Key };
        });
        getInstance().deleteMultipleObject(
          {
            Bucket,
            Region,
            Objects,
          },
          function (delError, deleteResult) {
            if (delError) {
              console.log("delete error", delError);
              reject(delError);
            } else {
              resolve();
            }
          }
        );
      }
    );
  });

export const listIcons = async (bandName) => {
  const Prefix = `icon/${bandName}/`;
  const res = await getInstance().getBucket({
    Bucket,
    Region,
    Prefix,
  });
  const files = res.Contents.filter((c) => c.Size && c.Size !== "0").map(
    (c) => c.Key
  );
  return files.map((f, i) => ({
    name: files[i].replace(Prefix, "").replace(".svg", ""),
    url: f,
  }));
};

export const addIcon = async (bandName, iconName, file) =>
  new Promise((resolve, reject) => {
    getInstance().putObject(
      {
        Bucket,
        Region,
        Key: `icon/${bandName}/${iconName}.svg`,
        Body: file,
        ContentType: "image/svg+xml",
      },
      function (err, data) {
        if (err) {
          reject(err);
        } else {
          resolve(data);
        }
      }
    );
  });

export const deleteIcon = async (bandName, iconName) =>
  new Promise((resolve, reject) => {
    getInstance().deleteObject(
      {
        Bucket,
        Region,
        Key: `icon/${bandName}/${iconName}.svg`,
      },
      function (err) {
        if (err) {
          console.log("delete error", err);
          reject(err);
        } else {
          resolve();
        }
      }
    );
  });

export const sign = (Key) =>
  getInstance().getObjectUrl({
    Bucket,
    Region,
    Key,
  });

export default cos;
